package com.itheima.wms.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.wms.common.constants.CodeConstant;
import com.itheima.wms.common.enums.GroudingStatus;
import com.itheima.wms.common.enums.ReceiptStatus;
import com.itheima.wms.common.enums.ReceivingStatus;
import com.itheima.wms.common.service.CrudServiceImpl;
import com.itheima.wms.dao.GroundingMapper;
import com.itheima.wms.dao.ReceiptListMapper;
import com.itheima.wms.dao.ReceiptMapper;
import com.itheima.wms.dao.ReceivingMapper;
import com.itheima.wms.entity.GroundingEntity;
import com.itheima.wms.entity.ReceiptEntity;
import com.itheima.wms.entity.ReceiptListEntity;
import com.itheima.wms.entity.ReceivingEntity;
import com.itheima.wms.factory.CodeWorker;
import com.itheima.wms.service.ReceiptListService;
import com.itheima.wms.service.ReceivingService;
import com.itheima.wms.service.StatusRecordService;
import com.itheima.wms.vo.BatchVO;
import com.itheima.wms.vo.ReceivingDetailVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * <p>
 * 业务实现类
 * 收货任务
 * </p>
 */
@Slf4j
@Service
public class ReceivingServiceImpl extends CrudServiceImpl<ReceivingMapper, ReceivingEntity> implements ReceivingService {

    @Autowired
    private ReceiptMapper receiptMapper;
    @Autowired
    private ReceiptListService receiptListService;
    @Autowired
    private GroundingMapper groundingMapper;

    @Autowired
    private StatusRecordService statusRecordService;

    @Override
    @Transactional
    public BatchVO complete(List<Long> ids) {
        BatchVO.BatchVOBuilder batchVOBuilder = BatchVO.builder();
        ids.forEach(id -> {
            ReceivingEntity receivingEntity = this.getById(id);
            if (null == receivingEntity) {
                log.info("id:{} 未找到", id);
                return;
            }

            // 校验清单是否有未填写的
            LambdaQueryWrapper<ReceiptListEntity> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(ReceiptListEntity::getMasterId, receivingEntity.getMasterId());
            List<ReceiptListEntity> receiptListEntities = receiptListService.list(wrapper);
            receiptListEntities = receiptListEntities.stream().filter(item -> null != item.getRealNum()).collect(Collectors.toList());
            if (CollectionUtils.isEmpty(receiptListEntities)) {
                log.info("id:{} 清单未填写完成", id);
                batchVOBuilder.error(receivingEntity.getCode() + "未完成收货确认");
                return;
            }

            if (receivingEntity.getStatus() != ReceivingStatus.RECEIVING.getCode()) {
                log.info("id:{} 状态不符 status:{}", id, receivingEntity.getStatus());
                batchVOBuilder.error(receivingEntity.getCode() + "状态不合法");
                return;
            }

            LambdaQueryWrapper<GroundingEntity> groundingWrapper = new LambdaQueryWrapper<>();
            groundingWrapper.eq(GroundingEntity::getMasterId, receivingEntity.getMasterId());
            Integer groundingCount = groundingMapper.selectCount(groundingWrapper);
            if (groundingCount > 0) {
                log.info("id:{} 已生成过上架任务", id);
                batchVOBuilder.error(receivingEntity.getCode() + "已生成过上架任务");
                return;
            }

            receiptListService.buildLocationPlanByReceipt(receivingEntity.getMasterId());

            // 修改收货任务状态 为 收货完成
            receivingEntity.setStatus(ReceivingStatus.COMPLETED.getCode());
            receivingEntity.setCompletionTime(LocalDateTime.now());
            this.updateById(receivingEntity);
            statusRecordService.saveStatus(receivingEntity);

            // 修改入库单状态 为 收货完成
            ReceiptEntity receiptEntity = receiptMapper.selectById(receivingEntity.getMasterId());
            receiptEntity.setStatus(ReceiptStatus.RECEIVING_COMPLETED.getCode());
            receiptMapper.updateById(receiptEntity);
            statusRecordService.saveStatus(receiptEntity);

            // 生成上架任务
            GroundingEntity groundingEntity = new GroundingEntity();
            BeanUtils.copyProperties(receiptEntity, groundingEntity);
            groundingEntity.setMasterId(receiptEntity.getId());
            groundingEntity.setCode(CodeWorker.nextCode(CodeConstant.GROUNDING));
            groundingEntity.setReceiptCode(receiptEntity.getCode());
            groundingEntity.setStatus(GroudingStatus.NEW.getCode());  //初始状态
            groundingEntity.setRealNum(receivingEntity.getRealNum());
            groundingEntity.setId(null);
            groundingMapper.insert(groundingEntity);
            statusRecordService.saveStatus(groundingEntity);

            // 修改入库单状态 为 上架中
            receiptEntity.setStatus(ReceiptStatus.GROUNDING.getCode());
            receiptMapper.updateById(receiptEntity);
            statusRecordService.saveStatus(receiptEntity);
            batchVOBuilder.result(groundingEntity.getCode());
        });
        return batchVOBuilder.build();
    }

    @Override
    public IPage<ReceivingDetailVO> pageDetail(Page<ReceivingDetailVO> page, Map data) {
        IPage<ReceivingDetailVO> iPage = this.baseMapper.selectReceivingDetail(page, data);
        return iPage;
    }
}

